<template>
	<cl-page>
		<view class="goods-detail">
			<!-- 自定义导航栏 -->
			<cl-topbar
				:border="false"
				:ref="setRefs('topbar')"
				with-mp
				background="transparent"
				:opacity="navOpacity"
			>
				<template #prepend>
					<view class="nav-action" @tap="refs.topbar?.back">
						<cl-icon name="arrow-left" size="20" color="#ffffff"></cl-icon>
					</view>
				</template>

				<template #append>
					<view class="nav-actions">
						<view class="nav-action" @tap="handleShare">
							<cl-icon name="share" size="18" color="#ffffff"></cl-icon>
						</view>
						<view class="nav-action" @tap="toCart">
							<cl-icon name="shopping-cart" size="18" color="#ffffff"></cl-icon>
						</view>
					</view>
				</template>
			</cl-topbar>

			<!-- 商品图片区域 -->
			<view class="image-section">
				<swiper
					class="goods-swiper"
					:autoplay="false"
					:indicator-dots="true"
					indicator-color="rgba(255,255,255,0.5)"
					indicator-active-color="#ffffff"
					@change="onImageChange"
				>
					<swiper-item v-for="(image, index) in goodsImages" :key="index">
						<image
							:src="image"
							class="goods-image"
							mode="aspectFit"
							@tap="previewImage(index)"
						/>
					</swiper-item>
				</swiper>

				<!-- 收藏按钮 -->
				<view class="collect-action" @tap="toggleCollect">
					<view class="collect-btn" :class="{ active: isCollected }">
						<cl-icon
							:name="isCollected ? 'heart-fill' : 'heart'"
							size="24"
							:color="isCollected ? '#ff4757' : '#ffffff'"
						></cl-icon>
					</view>
					<text class="collect-text">{{ isCollected ? "已收藏" : "收藏" }}</text>
				</view>
			</view>

			<!-- 商品信息区域 -->
			<view class="info-section">
				<!-- 价格和基本信息 -->
				<view class="price-info">
					<view class="price-main">
						<text class="price-symbol">¥</text>
						<text class="price-value">{{ formatPrice(goods.price) }}</text>
						<text class="price-unit">/ {{ goods.unit }}</text>
					</view>
					<view class="price-tags">
						<view class="tag primary" v-if="goods.isPres === 1">处方药</view>
						<view class="tag success" v-if="isInStock">有库存</view>
						<view class="tag warning" v-if="isLowStock">库存紧张</view>
					</view>
				</view>

				<!-- 商品标题 -->
				<view class="goods-title">
					<text class="title-text">{{ goods.title }}</text>
					<text class="sub-title" v-if="goods.oracleGoodsName">{{
						goods.oracleGoodsName
					}}</text>
				</view>

				<!-- 服务承诺 -->
				<view class="service-promises">
					<view class="promise-item">
						<cl-icon name="shield-check" size="16" color="#52c41a"></cl-icon>
						<text class="promise-text">正品保障</text>
					</view>
					<view class="promise-item">
						<cl-icon name="truck" size="16" color="#52c41a"></cl-icon>
						<text class="promise-text">快速配送</text>
					</view>
					<view class="promise-item">
						<cl-icon name="refresh" size="16" color="#52c41a"></cl-icon>
						<text class="promise-text">无忧退换</text>
					</view>
				</view>

				<!-- 商品详细信息 -->
				<view class="goods-details">
					<view class="detail-item">
						<text class="detail-label">商品规格</text>
						<text class="detail-value">{{ goods.goodsSpec }}</text>
					</view>
					<view class="detail-item">
						<text class="detail-label">生产厂家</text>
						<text class="detail-value">{{ goods.manufacturer }}</text>
					</view>
					<view class="detail-item">
						<text class="detail-label">批准文号</text>
						<text class="detail-value">{{ goods.approvalNo }}</text>
					</view>
					<view class="detail-item">
						<text class="detail-label">药品剂型</text>
						<text class="detail-value">{{ goods.formula }}</text>
					</view>
					<view class="detail-item">
						<text class="detail-label">包装规格</text>
						<view class="detail-value">
							<view class="package-info">
								<text class="package-type">{{
									goods.midpack > 1 ? "中包装" : "件包装"
								}}</text>
								<text class="package-desc" v-if="goods.midpack > 1"
									>{{ goods.midpack }}{{ goods.unit }}</text
								>
							</view>
							<view class="package-sale" v-if="goods.midpack > 1">
								<text
									:class="[
										'sale-status',
										goods.isMidpackSaleDisabled === 0 ? 'allow' : 'forbid',
									]"
								>
									{{
										goods.isMidpackSaleDisabled === 0
											? "支持拆零"
											: "不支持拆零"
									}}
								</text>
							</view>
						</view>
					</view>
					<view class="detail-item">
						<text class="detail-label">库存数量</text>
						<text class="detail-value" :class="{ 'low-stock': isLowStock }">
							{{ goods.storNum }}{{ goods.unit }}
						</text>
					</view>
				</view>

				<!-- 商品评价预览 -->
				<view class="comments-preview" @tap="toComments">
					<view class="preview-header">
						<text class="preview-title">商品评价</text>
						<view class="preview-action">
							<text class="action-text">查看全部</text>
							<cl-icon name="arrow-right" size="12" color="#666"></cl-icon>
						</view>
					</view>
					<view class="comment-item" v-if="latestComment">
						<view class="comment-user">
							<image
								:src="latestComment.avatarUrl || '/static/empty/no.jpg'"
								class="user-avatar"
							></image>
							<text class="user-name">{{
								latestComment.nickName || "匿名用户"
							}}</text>
							<view class="comment-stars">
								<cl-icon
									v-for="i in 5"
									:key="i"
									name="star-fill"
									size="12"
									:color="
										i <= (latestComment.starCount || 5) ? '#ffb800' : '#ddd'
									"
								></cl-icon>
							</view>
						</view>
						<text class="comment-content">{{ latestComment.content }}</text>
					</view>
				</view>
			</view>

			<!-- 商品详情内容 -->
			<view class="content-section" v-if="goods.content">
				<view class="section-title">商品详情</view>
				<view class="content-html">
					<!-- 这里应该渲染HTML内容，可以使用mp-html等组件 -->
					<text class="content-text">{{ goods.content }}</text>
				</view>
			</view>

			<!-- 底部操作栏 -->
			<view class="bottom-actions">
				<view class="action-left">
					<view class="action-item" @tap="toChat">
						<cl-icon name="headset" size="20" color="#666"></cl-icon>
						<text class="action-text">客服</text>
					</view>
					<view class="action-item" @tap="toCart">
						<cl-icon name="shopping-cart" size="20" color="#666"></cl-icon>
						<text class="action-text">购物车</text>
						<view class="cart-badge" v-if="cartCount > 0">{{ cartCount }}</view>
					</view>
				</view>
				<view class="action-right">
					<view class="action-btn add-cart" @tap="addToCart">
						<text class="btn-text">加入购物车</text>
					</view>
					<view class="action-btn buy-now" @tap="buyNow">
						<text class="btn-text">立即购买</text>
					</view>
				</view>
			</view>

			<!-- 规格选择弹窗 -->
			<spec-selector
				:show="showSpecSelector"
				:goods="goods"
				:mode="specMode"
				@close="showSpecSelector = false"
				@confirm="onSpecConfirm"
			/>
		</view>
	</cl-page>
</template>

<script lang="ts" setup>
import { ref, computed } from "vue";
import { onReady, onPageScroll } from "@dcloudio/uni-app";
import { router, useCool } from "/@/cool";
import { useUserStore } from "/@/cool/store";
import SpecSelector from "./components/spec-selector.vue";

const { service, refs, setRefs } = useCool();
const userStore = useUserStore();

// 页面数据
const goods = ref<any>({});
const latestComment = ref<any>(null);
const isCollected = ref(false);
const cartCount = ref(0);
const showSpecSelector = ref(false);
const specMode = ref<"cart" | "buy">("cart");
const navOpacity = ref(0);

// 计算属性
const goodsImages = computed(() => {
	const images = [];
	if (goods.value.mainPic) {
		images.push(goods.value.mainPic);
	}
	if (goods.value.pics && Array.isArray(goods.value.pics)) {
		images.push(...goods.value.pics);
	}
	return images.length > 0 ? images : ["/static/empty/no.jpg"];
});

const isInStock = computed(() => {
	return Number(goods.value.storNum || 0) > 0;
});

const isLowStock = computed(() => {
	return Number(goods.value.storNum || 0) < 10;
});

// 页面方法
async function loadGoodsDetail() {
	try {
		const goodsId = router.query.id;
		if (!goodsId) {
			uni.showToast({ title: "商品不存在", icon: "error" });
			return;
		}

		// 加载商品详情
		const goodsRes = await service.goods.info.info({ id: goodsId });
		goods.value = goodsRes || {};

		// 加载最新评价
		try {
			const commentRes = await service.goods.comment.page({
				goodsId,
				page: 1,
				size: 1,
			});
			latestComment.value = commentRes?.list?.[0] || null;
		} catch (error) {
			console.error("加载评价失败:", error);
		}

		// 检查收藏状态
		if (userStore.token) {
			try {
				const collectRes = await service.user.collect.collect({ goodsId });
				isCollected.value = !!collectRes;
			} catch (error) {
				console.error("检查收藏状态失败:", error);
			}
		}

		// 记录足迹
		if (userStore.token) {
			try {
				await service.user.footprint.recordFootprint({ goodsId });
			} catch (error: any) {
				console.error("记录足迹失败:", error);
			}
		}
	} catch (error) {
		console.error("加载商品详情失败:", error);
		uni.showToast({ title: "加载失败", icon: "error" });
	}
}

function formatPrice(price: any): string {
	const numPrice = Number(price);
	if (!numPrice || numPrice === 0 || isNaN(numPrice)) return "暂无报价";
	return numPrice.toFixed(2);
}

function onImageChange(e: any) {
	// 处理图片切换
}

function previewImage(index: number) {
	uni.previewImage({
		urls: goodsImages.value,
		current: index,
	});
}

async function toggleCollect() {
	if (!userStore.token) {
		router.push("/pages/user/login");
		return;
	}

	try {
		await service.user.collect.toggle({ goodsId: goods.value.id });
		isCollected.value = !isCollected.value;
		uni.showToast({
			title: isCollected.value ? "收藏成功" : "取消收藏",
			icon: "success",
		});
	} catch (error: any) {
		console.error("收藏操作失败:", error);
		uni.showToast({ title: error.message || "操作失败", icon: "none" });
	}
}

function addToCart() {
	if (!userStore.token) {
		router.push("/pages/user/login");
		return;
	}

	specMode.value = "cart";
	showSpecSelector.value = true;
}

function buyNow() {
	if (!userStore.token) {
		router.push("/pages/user/login");
		return;
	}

	specMode.value = "buy";
	showSpecSelector.value = true;
}

async function onSpecConfirm(spec: any) {
	try {
		if (specMode.value === "cart") {
			// 加入购物车
			await service.order.cart.addCart({
				goodsId: goods.value.id,
				count: spec.count,
			});
			uni.showToast({ title: "添加成功", icon: "success" });
		} else {
			// 立即购买
			router.push(`/pages/order/submit?goodsId=${goods.value.id}&count=${spec.count}`);
		}
	} catch (error: any) {
		console.error("操作失败:", error);
		uni.showToast({ title: error.message || "操作失败", icon: "none" });
	}
	showSpecSelector.value = false;
}

function handleShare() {
	// TODO: 实现分享功能
	uni.showShareMenu();
}

function toCart() {
	router.push("/pages/index/shopping-cart");
}

function toChat() {
	router.push("/uni_modules/cool-cs/pages/chat");
}

function toComments() {
	router.push(`/pages/goods/comment?goodsId=${goods.value.id}`);
}

// 页面滚动监听
onPageScroll((e) => {
	const opacity = Math.min(e.scrollTop / 300, 1);
	navOpacity.value = opacity;
});

onReady(() => {
	loadGoodsDetail();
});
</script>

<style lang="scss" scoped>
.goods-detail {
	background-color: #f8f9fa;
	min-height: 100vh;
	padding-bottom: 120rpx;
}

.nav-action {
	width: 72rpx;
	height: 72rpx;
	border-radius: 50%;
	background-color: rgba(0, 0, 0, 0.3);
	backdrop-filter: blur(10rpx);
	display: flex;
	align-items: center;
	justify-content: center;
}

.nav-actions {
	display: flex;
	gap: 16rpx;
}

.image-section {
	position: relative;
	height: 750rpx;
	background-color: #ffffff;
}

.goods-swiper {
	height: 100%;
}

.goods-image {
	width: 100%;
	height: 100%;
}

.collect-action {
	position: absolute;
	top: 120rpx;
	right: 32rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
}

.collect-btn {
	width: 88rpx;
	height: 88rpx;
	border-radius: 50%;
	background-color: rgba(0, 0, 0, 0.3);
	backdrop-filter: blur(10rpx);
	display: flex;
	align-items: center;
	justify-content: center;
	margin-bottom: 8rpx;
	transition: all 0.3s ease;

	&.active {
		background-color: rgba(255, 71, 87, 0.8);
	}
}

.collect-text {
	font-size: 20rpx;
	color: #ffffff;
	text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.5);
}

.info-section {
	background-color: #ffffff;
	margin: 16rpx;
	border-radius: 16rpx;
	padding: 32rpx;
}

.price-info {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 24rpx;
}

.price-main {
	display: flex;
	align-items: baseline;
}

.price-symbol {
	font-size: 28rpx;
	color: #ff4757;
	font-weight: 600;
}

.price-value {
	font-size: 48rpx;
	color: #ff4757;
	font-weight: 700;
	margin: 0 4rpx;
}

.price-unit {
	font-size: 24rpx;
	color: #666;
}

.price-tags {
	display: flex;
	gap: 12rpx;
}

.tag {
	padding: 8rpx 16rpx;
	border-radius: 20rpx;
	font-size: 20rpx;
	color: #ffffff;

	&.primary {
		background-color: #ff4757;
	}
	&.success {
		background-color: #52c41a;
	}
	&.warning {
		background-color: #faad14;
	}
}

.goods-title {
	margin-bottom: 24rpx;
}

.title-text {
	font-size: 32rpx;
	font-weight: 600;
	color: #1a1a1a;
	line-height: 1.4;
	margin-bottom: 8rpx;
	display: block;
}

.sub-title {
	font-size: 26rpx;
	color: #666;
	line-height: 1.3;
}

.service-promises {
	display: flex;
	gap: 32rpx;
	margin-bottom: 32rpx;
	padding: 24rpx;
	background-color: #f8f9ff;
	border-radius: 12rpx;
}

.promise-item {
	display: flex;
	align-items: center;
	gap: 8rpx;
}

.promise-text {
	font-size: 24rpx;
	color: #333;
}

.goods-details {
	border-top: 1rpx solid #eee;
	padding-top: 24rpx;
}

.detail-item {
	display: flex;
	align-items: flex-start;
	margin-bottom: 20rpx;

	&:last-child {
		margin-bottom: 0;
	}
}

.detail-label {
	width: 160rpx;
	font-size: 26rpx;
	color: #666;
	flex-shrink: 0;
}

.detail-value {
	flex: 1;
	font-size: 26rpx;
	color: #333;

	&.low-stock {
		color: #ff4757;
		font-weight: 600;
	}
}

.package-info {
	display: flex;
	align-items: center;
	gap: 12rpx;
	margin-bottom: 8rpx;
}

.package-type {
	padding: 4rpx 12rpx;
	background-color: #52c41a;
	color: #ffffff;
	border-radius: 8rpx;
	font-size: 20rpx;
}

.package-desc {
	font-size: 24rpx;
	color: #666;
}

.sale-status {
	font-size: 24rpx;

	&.allow {
		color: #52c41a;
	}
	&.forbid {
		color: #ff4757;
	}
}

.comments-preview {
	margin-top: 32rpx;
	padding-top: 24rpx;
	border-top: 1rpx solid #eee;
}

.preview-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 16rpx;
}

.preview-title {
	font-size: 28rpx;
	font-weight: 600;
	color: #1a1a1a;
}

.preview-action {
	display: flex;
	align-items: center;
	gap: 8rpx;
}

.action-text {
	font-size: 24rpx;
	color: #666;
}

.comment-item {
	padding: 20rpx;
	background-color: #f8f9ff;
	border-radius: 12rpx;
}

.comment-user {
	display: flex;
	align-items: center;
	gap: 12rpx;
	margin-bottom: 12rpx;
}

.user-avatar {
	width: 48rpx;
	height: 48rpx;
	border-radius: 50%;
}

.user-name {
	font-size: 24rpx;
	color: #333;
	flex: 1;
}

.comment-stars {
	display: flex;
	gap: 4rpx;
}

.comment-content {
	font-size: 26rpx;
	color: #666;
	line-height: 1.4;
}

.content-section {
	background-color: #ffffff;
	margin: 16rpx;
	border-radius: 16rpx;
	padding: 32rpx;
}

.section-title {
	font-size: 28rpx;
	font-weight: 600;
	color: #1a1a1a;
	margin-bottom: 20rpx;
}

.content-text {
	font-size: 26rpx;
	color: #666;
	line-height: 1.6;
}

.bottom-actions {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 120rpx;
	background-color: #ffffff;
	border-top: 1rpx solid #eee;
	display: flex;
	align-items: center;
	padding: 0 32rpx;
	z-index: 100;
}

.action-left {
	display: flex;
	gap: 40rpx;
}

.action-item {
	position: relative;
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 4rpx;
}

.action-text {
	font-size: 20rpx;
	color: #666;
}

.cart-badge {
	position: absolute;
	top: -8rpx;
	right: -8rpx;
	min-width: 32rpx;
	height: 32rpx;
	background-color: #ff4757;
	color: #ffffff;
	font-size: 20rpx;
	border-radius: 16rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 0 8rpx;
}

.action-right {
	flex: 1;
	display: flex;
	gap: 16rpx;
	margin-left: 40rpx;
}

.action-btn {
	flex: 1;
	height: 80rpx;
	border-radius: 40rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	transition: all 0.3s ease;

	&.add-cart {
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	}

	&.buy-now {
		background: linear-gradient(135deg, #ff4757 0%, #ff6b7a 100%);
	}

	&:active {
		transform: scale(0.95);
	}
}

.btn-text {
	font-size: 28rpx;
	color: #ffffff;
	font-weight: 600;
}
</style>
